package com.wswy.wzcx.api;

import android.text.TextUtils;

import com.blankj.utilcode.util.SPUtils;
import com.wswy.wzcx.BuildConfig;
import com.wswy.wzcx.model.DataCenter;
import com.wswy.wzcx.model.UserMode;
import com.wswy.wzcx.module.ChannelManager;
import com.wswy.wzcx.module.GlobalConfigManager;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;


class ReqParameter {

    static ReqParameter generate() {
        return new ReqParameter();
    }

    static ReqParameter generate(String key, String value) {
        return generate().add(key, value);
    }

    private Map<String, String> createMap() {
        Map<String, String> treeMap = new HashMap<>();
        treeMap.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));
        return treeMap;
    }

    private Map<String, String> mParams = createMap();


    ReqParameter add(String key, String value) {
        mParams.put(key, value);
        return this;
    }

    ReqParameter add(String key, int value) {
        mParams.put(key, String.valueOf(value));
        return this;
    }

    ReqParameter add(String key, long value) {
        mParams.put(key, String.valueOf(value));
        return this;
    }

    ReqParameter addAll(Map<String, String> map) {
        mParams.putAll(map);
        return this;
    }

    Map<String, String> getParams() {
        return getParams(true);
    }


    Map<String, String> getParams(boolean addToken) {
        mParams.put("channel", ChannelManager.getChannel());
        mParams.put("versionCode", String.valueOf(BuildConfig.VERSION_CODE));
        mParams.put("platform", Configs.PLATFORM);
        mParams.put("module", "weizhangchaxun");
        mParams.put("product", "12123");
        mParams.put("appId", Configs.APPID);

        mParams.put("uuid", SPUtils.getInstance().getString(GlobalConfigManager.SP_UUID_KEY));

        if (addToken) {
            UserMode userMode = DataCenter.get().getUserMode();
            if (userMode != null && userMode.token != null) {
                mParams.put("token", userMode.token);
            }
        }


        for (Iterator<Map.Entry<String, String>> iterator = mParams.entrySet().iterator();
             iterator.hasNext(); ) {

            Map.Entry<String, String> next = iterator.next();
            if (TextUtils.isEmpty(next.getValue())) {
                iterator.remove();
            }
        }
        return mParams;
    }

    Map<String, String> getSingedParams() {
        TreeMap<String, String> map = new TreeMap<>(getParams());

        String sign = ScUtil.ucSign(map);

        map.put("sign", sign);

        return map;
    }


}
